//
//  ArticalViewController.m
//  GiftNote
//
//  Created by lanou3g on 15/8/11.
//  Copyright (c) 2015年 GN. All rights reserved.
//

#import "ArticalViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "INHeader.h"
#import "GiftDetailCollectionViewCell.h"
#import "HomeDetailBuyViewController.h"
#import "Screen.h"
#import "MJRefresh.h"
#import "FMDB.h"
//  用判断刷新的方式(是下拉刷新还是上拉加载)
typedef NS_ENUM(NSInteger, RefreashType){
    RefreashTypeNew,  //  下拉刷新
    RefreashTypeMore     //  上拉加载
};


@interface ArticalViewController () <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, assign) NSInteger num;  // 每次加载的数据个数
@property (nonatomic, assign) RefreashType refreashType; //  刷新的方式

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) FMDatabase *db;
@end



@implementation ArticalViewController

#pragma mark --- 懒加载
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        self.dataArray = [NSMutableArray arrayWithArray:0];
    }
    return _dataArray;
}



#pragma mark --- 解析数据
- (void)createWithManger{
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger GET:[KSingleURL stringByAppendingString:[NSString stringWithFormat:@"%ld",(long)_num]] parameters:self success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (_refreashType == RefreashTypeNew) {
            [self.dataArray removeAllObjects];
            [self deleteData];
        }
        
        NSArray *arr = responseObject[@"data"][@"items"];
        for (NSDictionary *dic in arr) {

            GiftDetailModel *artiollerModel = [[GiftDetailModel alloc] init];
            [artiollerModel setValuesForKeysWithDictionary:dic[@"data"]];
            [self.dataArray addObject:artiollerModel];
            [self insertData:artiollerModel];
        }
        
        [_collectionView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error==%@",error);
    }];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createWithManger];
    self.navigationController.navigationBar.barTintColor = [UIColor orangeColor];

    self.collectionView.backgroundColor = [UIColor colorWithRed:240/256.0 green:250/256.0 blue:250/256.0 alpha:1];
    
    self.navigationItem.title = @"单品";
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[GiftDetailCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    
    
    //  设置一开始加载的数据个数以及调用刷新函数
    _num = 0;
    [self refreashData];
    
    [self creatDataBase];
    [self searchFromData];
}



#pragma mark --- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    GiftDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    GiftDetailModel *model = self.dataArray[indexPath.item];
    
    cell.layer.masksToBounds = YES;
    cell.layer.cornerRadius = 5;
    cell.model = model;
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}



#pragma mark --- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake((SCREEN_WIDTH - 20) / 2.0, (SCREEN_WIDTH - 20) / 2.0 + 80);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 5, 0, 5);
}



#pragma mark --- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeDetailBuyViewController *homeVC = [[HomeDetailBuyViewController alloc] init];
    GiftDetailModel *model = _dataArray[indexPath.item];
    
    homeVC.ID = [model.ID stringValue];
    

    [self.navigationController pushViewController:homeVC animated:YES];
}



#pragma mark --- action
- (void)refreashData{
    
    [self.collectionView addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(refeashNew)];
    [self.collectionView addGifFooterWithRefreshingTarget:self refreshingAction:@selector(refreashMore)];
}

//  刷新数据(重新开始加载)
- (void)refeashNew{
    
    _num = 0;
    _refreashType = RefreashTypeNew;
    [self createWithManger];
    [self.collectionView.gifHeader endRefreshing];
}

//  加载数据(加载一次,增加20条数据)
- (void)refreashMore{
    
    _num += 20;
    _refreashType = RefreashTypeMore;
    [self createWithManger];
    [self.collectionView.gifFooter endRefreshing];
}


#pragma mark - 数据持久化
// 创建数据库
- (void)creatDataBase{
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]stringByAppendingPathComponent:@"Artical.db"];
    //        NSLog(@"%@",path);
    _db = [FMDatabase databaseWithPath:path];
    
    if (![_db open]) {
        NSLog(@"打开数据库失败");
    }
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS ArticalList (id integer PRIMARY KEY, cover_image_url text, name text, price text, favorites_count text)"];
}



// 添加数据库
- (void)insertData:(GiftDetailModel *)model{
    
    NSString *str = [[[NSNumberFormatter alloc] init] stringFromNumber:model.favorites_count];
    
    [_db executeUpdate:@"INSERT INTO ArticalList (cover_image_url, name, price, favorites_count) VALUES (?,?,?,?)",model.cover_image_url, model.name, model.price, str];
}



//  删除数据库
- (void)deleteData{
    
    [_db executeUpdate:@"DELETE FROM ArticalList"];
}



// 查找数据库
- (void)searchFromData{
    
    FMResultSet *header = [_db executeQuery:@"SELECT * FROM ArticalList"];
    while ([header next]) {
        
        GiftDetailModel *model = [[GiftDetailModel alloc] init];
        model.cover_image_url = [header stringForColumn:@"cover_image_url"];
        model.name = [header stringForColumn:@"name"];
        model.price = [header stringForColumn:@"price"];
        
        NSString *str = [header stringForColumn:@"favorites_count"];
        NSInteger num = [str intValue];
        model.favorites_count = @(num);
        [self.dataArray addObject:model];
    }
    [header close];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
